<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">会员配置</div> -->
    <div v-if="meta.indexOf('OptionVipAdd') > -1" class="doumee-table-buttons">
      <el-button v-if="meta.indexOf('OptionVipAdd') > -1" type="primary" @click="toAmountAdd(0)">{{ translate("add") }}</el-button>
    </div>
    <el-table ref="table1" :data="listAmount" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
      <el-table-column align="center" :label="translate('hyczgdjepz')" prop="name" min-width="300" />
      <el-table-column align="center" :label="translate('status')" min-width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isAllow" v-preventReClick :active-value="'1'" :inactive-value="'0'" :disabled="meta.indexOf('OptionVipEdit') == -1" @change="changeConfig($event, scope.row.id, 'isAllow', 'amount')" />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="translate('sort')" prop="sort" min-width="200" />
      <el-table-column align="center" width="1" />
      <el-table-column :label="translate('handle')" align="center" fixed="right" min-width="200">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="meta.indexOf('OptionVipEdit') > -1" v-preventReClick type="text" @click="toAmountAdd(1, scope.row)">{{ translate("edit") }}</el-button>
            <el-button v-if="meta.indexOf('OptionVipDel') > -1" v-preventReClick type="text" style="color: red" @click="toDeleteAmount(scope.row.id)">{{ translate("del") }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex-cc doumee-pagination">
      <el-pagination :hide-on-single-page="true" background layout="prev, pager, next" :total="total" />
    </div>

    <el-table ref="table2" :data="listDiscount" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
      <el-table-column align="center" :label="translate('youhuigj')" prop="name" min-width="300" />
      <el-table-column align="center" :label="translate('supportEditf')">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isEdit" v-preventReClick :active-value="'1'" :inactive-value="'0'" @change="changeConfig($event, scope.row.id, 'isEdit', 'discount')" />
        </template>
      </el-table-column>
      <el-table-column align="center" :label="translate('desc')" prop="description" min-width="300" />
    </el-table>

    <div style="height: 40px" />

    <el-table ref="table3" :data="listWX" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
      <el-table-column align="center" :label="translate('wechatSite')" width="500">
        <template slot-scope="scope">
          <div class="flex-c">
            <div style="flex: 1; text-align: left; display: block">
              {{ scope.row.name }}
              <el-button v-if="
                  meta.indexOf('OptionVipBook') > -1 &&
                    scope.row.code === 'APP_SITE_BOOK_DAY'
                " type="primary" @click="isShowMemSiteCon = true">{{ translate("mmeberSiteCon") }}</el-button>
              <!-- 退款规则修改 -->
              <el-button v-if=" scope.row.code === 'VENUE_SITE_TK_MODE'" type="primary" @click="isShowMemSiteConRule = true">{{ translate("tkgz") }}</el-button>
            </div>
            <el-input v-model="scope.row.value" style="width: 120px" placeholder="" size="normal" @change="editWXItem(scope.row)" />
          </div>
        </template>

      </el-table-column>
      <el-table-column align="center" :label="translate('desc')" prop="description" min-width="500" />
    </el-table>

    <!-- 新增节假日配置 -->
    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="translate('hyczgdjepz')" :visible.sync="showAmountAddData">
      <el-form ref="refForm" :rules="rules" :model="amountAddData" label-width="auto">
        <el-form-item :label="translate('fexMoney')" prop="name">
          <el-input v-model="amountAddData.name" maxlength="10" autocomplete="off" onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')" oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}" />
        </el-form-item>
        <el-form-item :label="translate('enableFlag')">
          <el-switch v-model="amountAddData.isAllow" :active-value="'1'" :inactive-value="'0'" />
        </el-form-item>
        <el-form-item :label="translate('sort')" prop="sort">
          <el-input v-model="amountAddData.sort" maxlength="10" autocomplete="off" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAmountAddData = false">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="formOnSubmit('refForm')">{{ translate("enter") }}</el-button>
      </div>
    </el-dialog>

    <!-- 会员订场配置 -->
    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="translate('mmeberSiteCon')" :visible.sync="isShowMemSiteCon" width="800px">
      <span class="warnningTip">{{ translate("supportMemCon") }}</span>
      <div class="memSite_wrap">
        <div v-for="item in cardList" :key="item.id" class="item">
          <div class="label">{{ item.cardName }}：</div>
          <el-input v-model="item.value" oninput="value=value.replace(/^(0+)|[^\d]+/g, '').slice(0, 5)" class="w200" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowMemSiteCon = false">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="memSiteSub">{{ translate("enter") }}</el-button>
      </div>
    </el-dialog>
    <!-- 退款规则 -->
    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="translate('jtstkgz')" @close="close" :visible.sync="isShowMemSiteConRule" width="800px">
      <span class="warnningTip">退款规则默认适用于会员小程序，可选择是否适用于场馆端</span>
      <!-- <video style="height: 100px;width: 100px;" id="videoElement"></video> -->
      <!-- <video ref="videoElement" id="videoElement" style="width: 640px; height: 360px" controls></video> -->
      <div class="memSite_wrap">
        <el-table :data="rateList" border>
          <el-table-column align="center" label="申请退票距开场时间" prop="name" min-width="300">
            <template slot-scope="scope">
              <div class="flex-cc" v-if="scope.$index === 0">
                <el-input v-model="scope.row.timeStart" @input="handleTimeInput(scope.row, 'timeStart')" style="width:60px;" />
                <span class="ml10">小时以上(含)</span>
              </div>
              <div class="flex-cc" v-else>
                <el-input v-model="scope.row.timeStart" @input="handleTimeInput(scope.row, 'timeStart')" style="width:60px;" />
                <span class="ml10">小时(含) - </span>
                <el-input :value="scope.row.timeEnd || (scope.$index > 0 ? rateList[scope.$index - 1].timeStart : '')" readonly @focus="copyPreviousTimeEnd(scope.row)" style="width:60px;margin-left:6px;" />
                <span class="ml10">小时(不含)</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="退票费用" prop="sort" min-width="200">
            <template slot-scope="scope">
              <div class="flex-cc">
                <!-- <el-input v-if="scope.$index === 0" v-model="wu" readonly style="width:65px;" /> -->
                <span v-if="scope.$index === 0">无</span>
                <el-input v-else v-model="scope.row.rate" oninput="value=value.replace(/[^\d.]/g, '').replace(/^\./, '0.').replace(/(\.\d{2})\d*/g, '$1').slice(0, 8)" style="width:75px;" />
                <span v-if="scope.$index !== 0" class="ml10">%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="translate('handle')" align="center">
            <template slot-scope="scope">
              <!-- <div class="flex-cc"> -->
              <el-button v-if="scope.$index === 0" type="text" @click="addTicketRule(scope.row)">{{translate('add')}}</el-button>
              <el-button v-if="scope.$index !== 0" type="text" @click="deleteTicketRule(scope.row)">{{translate('del')}}</el-button>
              <!-- </div> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick :loading="subLoadingRule" type="primary" @click="addRateList">{{ translate("enter") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  memberSiteConfigSet,
  cardList,
  configList,
  configUpdate,
  configAdd,
  configDelete,
  getRateList,
  editRateList,
} from '@/api'
export default {
  name: 'OptionVip',
  data () {
    return {
      modalDialog: this.$store.state.app.dialog,
      subLoading: false,
      subLoadingRule: false,
      meta: [],
      listAmount: [],
      listDiscount: [],
      listWX: [],
      cardList: [],
      isShowMemSiteCon: false,
      isShowMemSiteConRule: false,
      wu: '无',
      memSiteConfig: {},
      pagination: {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      },
      total: 0,
      amountAddEdit: 0,
      showAmountAddData: false,
      amountAddData: {
        name: '',
        isAllow: '1',
        sort: '',
        type: '5'
      },
      rules: {
        name: [{ required: true, message: this.translate('fexMoneyP'), trigger: 'blur' }],
        sort: [{ required: true, message: this.translate('sortPlace'), trigger: 'blur' }]
      },
      rateList: [
        { timeStart: '', timeEnd: '', rate: '' },
      ],
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.getConfig()
    this.getRateList()
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.table1.doLayout()
      this.$refs.table2.doLayout()
      this.$refs.table3.doLayout()
    })
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table1.doLayout()
      this.$refs.table2.doLayout()
      this.$refs.table3.doLayout()
    })
  },
  watch: {
    rateList: {
      handler (newVal) {
        newVal.forEach((row, index) => {
          if (index > 0) {
            this.$set(row, 'timeEnd', newVal[index - 1].timeStart);
          }
        });
      },
      deep: true,
    },
  },
  methods: {
    handleTimeInput (row, field) {
      // 处理时间输入的逻辑
      const value = row[field].trim(); // 去除输入值的前后空格
      const parsedValue = parseFloat(value); // 使用parseFloat来允许小数

      // 检查是否是一个有效的数字，并且不是NaN
      if (isNaN(parsedValue)) {
        this.$set(row, field, ''); // 如果不是有效数字，则设置为空字符串
        return;
      }

      // 检查timeEnd是否存在，并且确保timeStart不大于timeEnd
      if (row.timeEnd !== undefined && row.timeEnd !== null && parsedValue >= row.timeEnd) {
        this.$message.error('开始时间不能大于等于结束时间'); // 显示错误消息（需要Element UI的message组件）
        this.$set(row, field, row[field].slice(0, -1)); // 回退一个字符（简单处理，可能需要更复杂的UI反馈）
        return;
      }
      let val = value.replace(/[^\d.]|(\.\d{2,})|^0+(?=\d)/g, '').slice(0, 6)
      //    oninput = "value=
      // 设置值（使用this.$set来确保响应性）
      this.$set(row, field, val); // 保留一位小数
    },
    copyPreviousTimeEnd (row) {
      // 这个方法在focus事件中已经绑定，但实际操作可以在数据更新时自动处理
      if (this.rateList.length > row.$index + 1) {
        this.$set(row, 'timeEnd', this.rateList[row.$index - 1].timeStart);
      }
    },
    addTicketRule () {
      console.log(this.rateList, '4544')
      // 添加新规则的逻辑
      const newRow = { timeStart: '', timeEnd: '', rate: '' };
      this.rateList.push(newRow);
      console.log(this.rateList, 'rateList9999')
    },
    deleteTicketRule (row) {
      // 删除规则的逻辑
      const index = this.rateList.indexOf(row);
      this.rateList.splice(index, 1);
    },
    close () {
      this.isShowMemSiteConRule = false
      this.subLoadingRule = false
      this.getRateList()
    },
    getRateList (id) {
      getRateList({ param: {} }).then((res) => {
        if (res.errorCode === '000000') {
          this.rateList = []
          let list = res.recordList.reverse() || []
          if (list.length > 0) {
            list.map(item => item.rate = (item.rate * 100).toFixed(2))
            const resultLists = list.map((item, index) => {
              if (index < list.length - 1) {
                // 除了最后一条数据，将当前数据的timeStart设置为下一条数据的time
                item.timeStart = list[index + 1].time;
              } else {
                // 对于最后一条数据，可以根据需求设置默认值或者保持原有属性（这里设置为null）
                item.timeStart = 0;
              }
              return item;
            });
            const newData = { timeStart: resultLists[0].time, };
            const newList = [newData, ...resultLists]; // 将新数据放在前面，原数组元素依次往后排列
            this.rateList = newList
          } else {
            this.rateList = [{ timeStart: null, timeEnd: null, rate: null }]
          }
        }
      })
    },
    addRateList () {
      let flag = false
      let flags = false
      //   let indexFlag = false
      if (this.rateList.length === 1) {
        this.$message.warning('不符合提交规则')
        return
      }
      const first = this.rateList[0].timeStart;
      const sec = this.rateList[1].timeStart;
      const starts = Number(first);
      const secs = Number(sec);
      let indexFlag = starts > secs
      if (indexFlag == false) {
        flag = true
      }
      console.log(indexFlag, 'indexFlag')
      console.log(this.rateList, 'rateList')
      this.rateList.map((item, index) => {
        const start = Number(item.timeStart);
        const end = Number(item.timeEnd);
        if (!isNaN(start) && !isNaN(end) && index != 0) {
          if (start >= end) {
            console.log(start > end, '777');
            console.log(`第 ${index + 1} 条数据的 timeStart (${start}) 不小于 timeEnd (${end})`);
            flag = true
          }
        }
        if (index === this.rateList.length - 1 && item.timeStart != 0) {
          flags = true;
        }
        if (item.timeStart === '' || item.rate === '') {
          console.log('请填写完整')
          flag = true
        }
      })

      if (flag) {
        this.$message.warning('请先添加退款规则,请检查退票费用或开场时间是否填写完整/错误')
        return
      }
      if (flags) {
        this.$message.warning('阶梯式退款规则必须以0为开始时间')
        return
      }
      let list = this.rateList;
      const [, ...newLists] = list;
      let newList = newLists.map(item => ({
        ...item,
        time: Number(item.timeEnd),
        rate: (item.rate / 100).toFixed(4)
      }));
      list = newList;
      this.subLoadingRule = true
      editRateList({ param: { rateList: list } }).then((res) => {
        this.subLoadingRule = false
        if (res.errorCode === '000000') {
          this.$message.success(this.translate('handleScs'))
          this.isShowMemSiteConRule = false
          this.rateList = []
          //   this.getRateList()
        }
      })
    },
    // 获取配置项
    async getConfig () {
      // 会员充值配置
      configList({ param: { type: '5' } }).then((res) => {
        this.listAmount = res.recordList
        this.total = res.totalCount
        const t = res.totalCount / 10
        const count = Number(t.toFixed(0)) + (t - t.toFixed(0) > 0 ? 1 : 0)
        this.total = count * 10
      })
      // 优惠改价/赠送金额配置
      configList({ param: { type: '6' } }).then((res) => {
        if (res.errorCode === '000000') {
          this.listDiscount = res.recordList
        }
      })
      // 微信场地配置
      configList({ param: { type: '7' } }).then((res) => {
        if (res.errorCode === '000000') {
          this.listWX = res.recordList
        }
      })
      const cardRes = await cardList({ param: { type: '1' } })
      this.cardList = cardRes.recordList.map((item) => {
        item.value = null
        return item
      })
      // 会员场地配置项
      configList({ param: { type: '20' } }).then((res) => {
        if (res.errorCode === '000000') {
          this.memSiteConfig = res.recordList
          this.cardList.forEach((item) => {
            this.memSiteConfig.forEach((item2) => {
              if (item.id === item2.name) {
                item.value = item2.value
              }
            })
          })
        }
      })
    },
    memSiteSub () {
      const temp = this.cardList.filter((i) => i.value)
      if (temp.length === 0) { return this.$message.warning(this.translate('qsrhydyts')) }
      const list = temp.map((item) => {
        return {
          name: item.id,
          value: item.value
        }
      })

      this.subLoading = true
      memberSiteConfigSet({ param: { list } }).then(
        (res) => {
          this.subLoading = false
          if (res.errorCode !== '000000') return
          this.$message.success(this.translate('configScs'))
          this.isShowMemSiteCon = false
          this.getConfig()
        },
        () => {
          this.subLoading = false
        }
      )
    },
    // getCardList() {
    //   cardList({ param: { type: '1' }}).then(res => {
    //     this.cardList = res.recordList || []
    //   })
    // },
    // 添加/编辑会员充值配置
    toAmountAdd (type, data) {
      this.amountAddEdit = type
      this.showAmountAddData = true
      if (type) {
        this.amountAddData = data
      }
    },
    formOnSubmit (formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.confirmAmountAdd()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 确认添加/编辑会员充值配置
    confirmAmountAdd () {
      const { amountAddData: param, amountAddEdit } = this
      if (amountAddEdit) {
        this.subLoading = true
        // 编辑
        configUpdate({ param }).then(
          (res) => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              this.getConfig()
              this.showAmountAddData = false
              this.amountAddData = {
                name: '',
                isAllow: '1',
                sort: '',
                type: '5'
              }
            }
          },
          () => {
            this.subLoading = false
          }
        )
      } else {
        // 新增
        configAdd({ param }).then(
          (res) => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              this.getConfig()
              this.showAmountAddData = false
              this.amountAddData = {
                name: '',
                isAllow: '1',
                sort: '',
                type: '5'
              }
            }
          },
          () => {
            this.subLoading = false
          }
        )
      }
    },
    // 删除会员充值配置
    toDeleteAmount (id) {
      this.$confirm(this.translate('xiangDelPlace'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('cancel'),
        type: 'warning'
      })
        .then(() => {
          configDelete({ param: { id } }).then((res) => {
            if (res.errorCode === '000000') {
              this.$message.success(this.translate('delScs'))
              this.getConfig()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.translate('canceledDel')
          })
        })
    },
    // 切换 会员充值配置状态、优惠改价/赠送金额是否支持修改
    changeConfig (data, id, name, type_) {
      const param = { id }
      param[name] = data
      switch (type_) {
        case 'amount':
          param.type = '5'
          break

        case 'discount':
          param.type = '6'
          break

        default:
          break
      }
      configUpdate({ param }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success(this.translate('editScs'))
        }
      })
    },
    // 修改微信场地
    editWXItem (param) {
      configUpdate({ param }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success(this.translate('editScs'))
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.memSite_wrap {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 50%;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .label {
      flex: 1;
      text-align: right;
    }
  }
}
</style>
